#!/usr/bin/env python3
# vim: tabstop=4 expandtab

import datetime, time
from urllib.parse import unquote
from os import getenv
from os.path import exists
import string
import random
import URLHelper
import antennaDB
import signoffs

def randomFileName():
    return ''.join(random.choice(string.ascii_letters) for x in range(32))

filterFile = getenv('PATH_INFO')
filterFilePathParts = filterFile.split("/")
if "" in filterFilePathParts:
    filterFilePathParts.remove("")
db = antennaDB.AntennaDB()
lastRead = "Last Read:" + str(int(time.mktime(datetime.datetime.utcnow().utctimetuple()))) + "\n"

if not filterFile or not exists("customfilters/"+filterFilePathParts[0]):
    if not getenv('QUERY_STRING') or not getenv('QUERY_STRING').lower() in ["y","ye","yes"]:
        print("10 Type 'y' if you want to create a filter, otherwise go back.\r")
    else:
        filterFile = randomFileName()
        while exists("customfilters/"+filterFile):
            filterFile = randomFileName()
        with open("customfilters/"+filterFile, "w") as f:
            f.write(lastRead)
        print("30 gemini://"+getenv('SERVER_NAME')+getenv('SCRIPT_NAME')+"/"+filterFile+"\r")

else:
    f = open("customfilters/"+filterFilePathParts[0], "r")
    rules = f.read().split("\n")
    f.close()

    f = open("customfilters/"+filterFilePathParts[0], "w")

    rules = list(filter(("").__ne__, rules))
    rules.pop(0)
    affectedRule = getenv('QUERY_STRING')

    if filterFilePathParts[-1] == "add":
        if not affectedRule:
            print("10 Rule to add:\r\n")
        else:
            rules.insert(0,unquote(affectedRule))
            print("30 gemini://"+getenv('SERVER_NAME')+getenv('SCRIPT_NAME')+"/"+filterFilePathParts[0]+"\r\n")

    elif filterFilePathParts[-1] == "remove":
        if not affectedRule or not affectedRule in rules:
            print("10 Rule to remove:\r\n")
        else:
            rules.remove(affectedRule)
            print("30 gemini://"+getenv('SERVER_NAME')+getenv('SCRIPT_NAME')+"/"+filterFilePathParts[0]+"\r\n")

    elif filterFilePathParts[-1] == "read":
        print("20 text/gemini\r")
        print("# Your Filter Rules\n")
        if not rules:
            print("Bookmark this URL. It's your personal filter. It'll be here forever if you check it often, but if you don't check it in 90 days it'll be removed.\n\nYou should add some rules here! The way it works is that any link on Antenna that starts with a matching rule is removed from this view.\n\nFor example: the rule \"gemini://rockstar\" will remove every link starting with that, including \"gemini://rockstar.com/posts/1\" or \"gemini://rockstarfamily.org\"\n")
        for rule in rules:
            print("=> remove?"+rule+" "+rule+" (Click to remove)")
        print("")
        feedURLSet = set()
        for entry in db.getEntries():
            if entry.feedurl in rules:
                continue
            feedURLSet.add(entry.feedurl)
        for feedURL in feedURLSet:
            print("=> add?"+feedURL+" Click to block '"+feedURL+"'")
        print("\n=> "+getenv('SCRIPT_NAME')+"/"+filterFilePathParts[0]+"/add Click to add custom rule")

    else: # This is where we end up when we just want to read the feed.
        print("20 text/gemini\r")
        print("=> "+getenv('SCRIPT_NAME')+"/"+filterFilePathParts[0]+"/read Configure your filter.\n")
        print("# Your Filtered Feed")
        datestamp = "0000-00-00"
        for entry in db.getEntries():
            blocked = False
            for rule in rules:
                blocked = entry.link.startswith(rule) or entry.feedurl.startswith(rule)
                if blocked:
                    break
            if blocked:
                continue
            timestamp = datetime.datetime.utcfromtimestamp(entry.updated).strftime('%Y-%m-%d')
            if not datestamp == timestamp:
                datestamp = timestamp
                print("")
            print("=> " + entry.link + " " + timestamp + " " + entry.author + ": " + entry.title)

        print("\n> " + signoffs.getsig())
    f.write(lastRead + "\n".join(rules) + "\n")
    f.close()
